from django.shortcuts import HttpResponse
from django.http import JsonResponse
from django.urls.conf import path
from app.models import *
import requests
import json
import time
import os
import base64
import cv2

# 用于获取OPENid
openidUrl = 'https://api.weixin.qq.com/sns/jscode2session?'



# 用户登录
def Login(request):
    # 接收code
    if request.method == 'GET':
        code = request.GET.get('code')
        res = requests.get(
            url = openidUrl,
            params = {
                'appid':'wxeb73fda05f2dbb76',
                'secret':'078d137a23ac1fcc3d72aba44a7c4ecb',
                'js_code':code,
                'grant_type':'authorization_code'
            }
        ).json()
        openid = res['openid']
        # 判断该openid是否在用户表中，如果不在返回code404，在返回code200
        if(User.objects.filter(openID=openid).count()==1):
            return JsonResponse({'openid':openid,'code':200})
        else:
            return JsonResponse({'openid':openid,'code':404})
    elif request.method == 'POST':
        # 获取请求体
        postbody=request.body
        json_param = json.loads(postbody.decode())
        if json_param:
            imgUrl = json_param.get('imgUrl')
            nickname=json_param.get('nickname')
            openid=json_param.get('openid')
        print(imgUrl,nickname)
        # 注册用户
        user = User.objects.create(openID=openid,imgUrl=imgUrl,nickname=nickname)
        if user.id:
            return JsonResponse({'code':200,'user_id':user.id})
        else:
            return JsonResponse({'code':404})

# 获取用户进行中计划
def userPlaning(request):
    # 获取用户对象
    openid = request.GET.get('openid')
    user = User.objects.filter(openID=openid).first()
    plans = user.plans_set.filter(isdone=False)
    print(plans)
    data=[]
    for item in plans:
        dict={}
        dict['title']=item.name
        dict['Alldays']=item.Alldays
        dict['Seconds']=item.Seconds
        dict['doneDays']=item.doneDays
        dict['doneSec']=item.doneSec
        dict['id'] = item.id
        data.append(dict)
    return JsonResponse({'code':200,'data':data})

# 用户打卡动作，增加每日次数
def submitPlanSec(request):
    # 获取planId
    if request.method == 'GET':
        ID = request.GET.get('id')
        plan = Plans.objects.filter(id=ID).first()
        plan.doneSec=plan.doneSec+1
        plan.save()
        return HttpResponse(plan.doneSec)

def submitPlanDay(request):
    # 获取planId
    if request.method == 'GET':
        ID = request.GET.get('id')
        plan = Plans.objects.filter(id=ID).first()
        plan.doneSec=plan.doneSec+1
        plan.doneDays=plan.doneDays+1
        plan.save()
        return JsonResponse({'donesec':plan.doneSec,'doneday':plan.doneDays})

# 获取用户已完成计划
def userPlandone(request):
    # 获取用户对象
    openid = request.GET.get('openid')
    user = User.objects.filter(openID = openid).first()
    plans = user.plans_set.filter(isdone = True)
    data = []
    for item in plans:
        dict={}
        dict['title']=item.name
        dict['Alldays']=item.Alldays
        dict['Seconds']=item.Seconds
        dict['doneDays']=item.doneDays
        dict['doneSec']=item.doneSec
        data.append(dict)
    return JsonResponse({'code':200,'data':data})
# 添加计划
def addPlan(request):
    postbody=request.body
    json_param = json.loads(postbody.decode())
    if json_param:
        color = json_param.get('color')
        days=json_param.get('days')
        openid=json_param.get('openid')
        title=json_param.get('title')
        sec=json_param.get('sec')
        # 下面创建新的数据对象
        user=User.objects.filter(openID=openid).first()
        print(user)
        Plans.objects.create(color=color,name=title,Alldays=days,Seconds=sec,user_id=user.id)
        # 查询试试
        obj = Plans.objects.filter(user=user.id).first()
        print(obj.name)
    return HttpResponse('ok')
# 获取用户加入的小组
def userGroups(request):
    openid = request.GET.get('openid')
    print('收到请求,',openid)
    user = User.objects.filter(openID=openid).first()
    print('收到请求2,',openid)
    # 获取与user关联的group
    groups = user.groups.all()
    print(type(groups))
    groupData = []
    for item in groups:
        dict = {}
        dict['name']=item.name
        dict['des']=item.des
        dict['id']=item.id
        # 生成base64编码
        print(item.imgUrl)
        img_im= cv2.imread(item.imgUrl)
        print(img_im)
        imgUrl=base64.b64encode(cv2.imencode('.jpg',img_im)[1]).decode()
        dict['imgUrl'] = imgUrl   
        dict['personNum']=item.personNum
        groupData.append(dict)
    # datadict = json.dumps({'code':200,'data':groupData})
    # return HttpResponse(datadict)
    return JsonResponse({'code':200,'data':groupData})
# 创建小组
def addGroups(request):
    if request.method == 'POST':
        image = request.FILES['image']
        print(image)
        openid = request.POST.get('openid')
        name = request.POST.get('name')
        des = request.POST.get('des')
        appdir = os.path.dirname(__file__)
        BASEDIR = os.path.dirname(appdir)
        path = BASEDIR+"\\images\\groupImg\\"
        filepath = path+str(int(time.time()))+'.jpg'
        # 图片存储
        if not os.path.exists(filepath):
            with open(filepath,'wb') as f:
                f.write(image.read())
                f.close()
            # 创建数据
            group = Group.objects.create(name=name,des=des,imgUrl=filepath)
            user = User.objects.filter(openID=openid).first()
            user.groups.add(group)
            print(group.id,group.name,group.des,group.imgUrl)
            return HttpResponse('上传成功')
        else:
            return HttpResponse('上传失败')


# 获取所有小组
def allGroups(request):
    openid = request.GET.get('openid')
    # 获取用户已加入的小组
    user = User.objects.filter(openID=openid).first()
    usergroup = user.groups.all()
    usergroupid = []
    for item in usergroup:
        usergroupid.append(item.id)
    groups = Group.objects.filter()
    groupData=[]
    for item in groups:
        if item.id in usergroupid:
            continue
        dict={}
        dict['name']=item.name
        dict['id']=item.id
        dict['des']=item.des
        # 生成base64编码
        img_im= cv2.imread(item.imgUrl)
        imgUrl=base64.b64encode(cv2.imencode('.jpg',img_im)[1]).decode()
        dict['imgUrl'] = imgUrl        
        dict['personNum']=item.personNum
        groupData.append(dict)
    return JsonResponse({'code':200,'data':groupData})
# 加入小组  
def joinGroups(request):
    if request.method == 'POST':
        postbody=request.body
        json_param = json.loads(postbody.decode())
        if json_param:
            openid = json_param.get('openid')
            print(openid)
            groupid = json_param.get('groupid')
            print(groupid)
            user = User.objects.filter(openID=openid).first()
            group = Group.objects.filter(id=groupid).first()
            user.groups.add(group)
            return HttpResponse('ok')

# 获取用户计划数量，进行中数量，已完成数量，以及用户已发表动态
def getUserData(request):
    openid = request.GET.get('openid')
    user = User.objects.filter(openID=openid).first()
    allcou = user.plans_set.all().count()
    loadingcou = user.plans_set.filter(isdone=False).count()
    donecou = user.plans_set.filter(isdone=True).count()
    return JsonResponse({'allcou':allcou,'loadingcou':loadingcou,'donecou':donecou})
# 获取用户发表过的历史动态
def getUserDynamic(request):
    openid = request.GET.get('openid')
    user = User.objects.filter(openID=openid).first()
    dynamic = Dynamics.objects.filter(user=user).order_by('id')
    dynamicCou = dynamic.count()
    if dynamicCou!=0:
        data=[]
        for item in dynamic:
            user = item.user
            dict={}
            dict['nickname'] = user.nickname
            dict['userImg'] = user.imgUrl
            dict['content'] = item.content
            group = item.group
            dict['groupname'] = group.name
            dict['good'] = item.good
            if item.imgs != '':
                imgList = item.imgs.split(",")
                print(imgList)
                b64imgList = []
                for item in imgList:
                    print(item)
                    if item == '':
                        continue
                    img_im= cv2.imread(item)
                    imgUrl=base64.b64encode(cv2.imencode('.jpg',img_im)[1]).decode()
                    b64imgList.append(imgUrl)
                dict['imgList']=b64imgList
            data.append(dict)
        return JsonResponse({'code':'ok','data':data})
    else:
        return JsonResponse({'code':404})
# 发表动态(对上传图片的处理)
ID = ''
def getDynamicAddTxt(request):
    # 获取请求体
    print(222)
    postbody=request.body
    json_param = json.loads(postbody.decode())
    if json_param:
        content= json_param.get('content')
        openid = json_param.get('openid')
        groupid =  json_param.get('groupid')
    user = User.objects.filter(openID=openid).first()
    group = Group.objects.filter(id=groupid).first()
    print(content)
    # 创建数据对象
    dynamic = Dynamics.objects.create(content=content,group=group,user=user)    
    global ID
    ID = dynamic.id
    return HttpResponse(id)

def addDynamic(request):
    if request.method == 'POST':
        print(111)
        img = request.FILES['img']
        id = request.POST.get('id')
        print('***************'+str(ID)+'**********')
        appdir = os.path.dirname(__file__)
        BASEDIR = os.path.dirname(appdir)
        path = BASEDIR+"\\images\\dynamics\\"
        if img:
            filepath = path+str(time.time())+'.jpg'
            # 图片存储
            if not os.path.exists(filepath):
                with open(filepath,'wb') as f:
                    f.write(img.read())
                    f.close()
                dynamic = Dynamics.objects.filter(id=ID).first()
                dynamic.imgs = dynamic.imgs+','+filepath
                dynamic.save()
            return HttpResponse('上传成功')
        else:
            return HttpResponse('上传失败')

    
    
# 获取圈子动态
def getAllDynamic(request):
    groupid = request.GET.get('groupid')
    print(groupid)
    group = Group.objects.filter(id=groupid).first()
    dynamic = Dynamics.objects.filter(group=group).order_by('id')
    dynamicCou = dynamic.count()
    if dynamicCou!=0:
        data=[]
        for item in dynamic:
            user = item.user
            dict={}
            dict['nickname'] = user.nickname
            dict['userImg'] = user.imgUrl
            dict['content'] = item.content
            group = item.group
            dict['groupname'] = group.name
            dict['good'] = item.good
            if item.imgs != '':
                imgList = item.imgs.split(",")
                print(imgList)
                b64imgList = []
                for item in imgList:
                    print(item)
                    if item == '':
                        continue
                    img_im= cv2.imread(item)
                    imgUrl=base64.b64encode(cv2.imencode('.jpg',img_im)[1]).decode()
                    b64imgList.append(imgUrl)
                dict['imgList']=b64imgList
            data.append(dict)
        return JsonResponse({'data':data})
    else:
        return JsonResponse({'code':404})

# 获取所有动态
def getDynamic(request):
    dynamic = Dynamics.objects.filter().order_by('good')
    dynamicCou = dynamic.count()
    if dynamicCou!=0:
        data=[]
        for item in dynamic:
            user = item.user
            dict={}
            dict['nickname'] = user.nickname
            dict['userImg'] = user.imgUrl
            dict['content'] = item.content
            group = item.group
            dict['groupname'] = group.name
            dict['good'] = item.good
            if item.imgs != '':
                imgList = item.imgs.split(",")
                print(imgList)
                b64imgList = []
                for item in imgList:
                    print(item)
                    if item == '':
                        continue
                    img_im= cv2.imread(item)
                    imgUrl=base64.b64encode(cv2.imencode('.jpg',img_im)[1]).decode()
                    b64imgList.append(imgUrl)
                dict['imgList']=b64imgList
            data.append(dict)
        return JsonResponse({'code':'ok','data':data})
    else:
        return JsonResponse({'code':404})